package cn.com.dycc.party_work.apply.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.party_org.member.service.MemberNotFoundException;
import cn.com.dycc.party_work.apply.dao.ApplyDao;
import cn.com.dycc.party_work.apply.entity.Apply;
import cn.com.dycc.party_work.apply.entity.UserAndApply;
import cn.com.dycc.party_work.apply.param.ApplyParam;
import cn.com.dycc.party_work.apply.param.FindApplyParam;
import cn.com.dycc.task_manage.ordermain.dao.OrderMainDao;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.FileUtil;
import cn.com.dycc.util.IntegerUtil;
import cn.com.dycc.util.Paging;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * Description: 入党申请业务层实现
 * Author: Liket
 * Version: 1.0
 * Create Date Time: 2018年6月20日 下午2:42:49.
 * Update Date Time: 
 * @see
 */
@Service("applyService")
public class ApplyServiceImpl implements ApplyService{
	@Resource
	private ApplyDao applyDao;
	
	@Resource(name="paging")
	private Paging paging;
	
	@Resource
	private AttachDao attachDao;
	
	@Resource
	private OrderMainDao orderMainDao;
	
	/**
	 * 添加入党申请
	 */
	@SystemServiceLog(description=Constants.ADDAPPLY)
	public int addApply(ApplyParam apply,HttpServletRequest req) throws ApplyNotFoundException {

		String certificateReg = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
		if(apply==null){
			throw new ApplyNotFoundException("请填写申请资料！");
		}
		if(apply.getUser_pic()==null||apply.getUser_pic().trim().isEmpty()){
			throw new ApplyNotFoundException("请上传头像");
		}
		if(apply.getUser_id()==null||apply.getUser_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写申请人！");
		}
		if(apply.getDept_id()==null||apply.getDept_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写党组织！");
		}
		if(apply.getCertificate()==null||apply.getCertificate().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写身份证！");
		}
		
			
		if(!Pattern.matches(certificateReg,apply.getCertificate())){
			throw new ApplyNotFoundException("请填写正确的身份证号码！");
		}
		
		
		if(apply.getSex()==null||apply.getSex().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写性别！");
		}
		
		if(apply.getNative_place()==null||apply.getNative_place().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写籍贯！");
		}
		
		if(apply.getEducation()==null||apply.getEducation().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写学历！");
		}
		
		if(apply.getApply_flag()==null||apply.getApply_flag().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写入党标识！");
		}
		
		if(apply.getApply_date()==null){
			throw new ApplyNotFoundException("请填写申请时间！");
		}
		
		if(apply.getSponsor()==null||apply.getSponsor().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写介绍人！");
		}
		
		if(apply.getAddress()==null||apply.getAddress().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写地址！");
		}
		
		if(apply.getBirthday()==null||apply.getBirthday().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写出生日期！");
		}
		
		if(apply.getClass_id()==null||apply.getClass_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写职务！");
		}
		
		if(apply.getPost_id()==null||apply.getPost_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写岗位！");
		}
		
		if(apply.getTel()==null||apply.getTel().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写固定电话！");
		}
		
		if(!(IntegerUtil.isPhone(apply.getTel().trim()))){
			throw new ApplyNotFoundException("请填写正确的固定电话！");
		}
		
		if(apply.getTel_m()==null||apply.getTel_m().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写移动电话！");
		}
		
		if(!(IntegerUtil.isMobile(apply.getTel_m().trim()))){
			throw new ApplyNotFoundException("请填写正确的移动电话！");
		}
		
		apply.setCreate_date(new Timestamp(new Date().getTime()));
		HttpSession session = req.getSession();
		String user_id = (String) session.getAttribute("id");
		if(user_id==null){
			throw new ApplyNotFoundException("请重新登录！");
		}
		apply.setOpt_user_id(user_id);
		apply.setOrg_id((String)session.getAttribute("org_id"));
		
		apply.setUpdate_date(DateUtil.getNowDate(DateUtil.TIME_FMT));
		apply.setUpdate_user_id(user_id);
		
		
		/**
		 * 移动头像
		 */
		String newPath = FileUtil.moveImage(apply.getUser_pic(), "party_work");
		apply.setUser_pic(newPath);
		
		int n = applyDao.addApply(apply);
		if(n!=1){
			throw new ApplyNotFoundException("添加失败");
		}
		
		List<Attach> listAttach = new ArrayList<Attach>();
		
		if(apply.getListAttach()!=null&&!apply.getListAttach().trim().isEmpty()){
			String str=apply.getListAttach().trim();
			//System.out.println(str);
			JSONArray json=JSONArray.fromObject(str);
			//System.out.println("l="+listAttach.size());
        
			for(int i=0;i<json.size();i++){

				//System.out.println("打桩2："+json.get(i));
				Object check=json.get(i);
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				
	
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				Attach attach=new Attach();
				attach.setMessage_no(apply.getApply_id());
				attach.setAttach_type(1);
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id((String)session.getAttribute("org_id"));
				attach.setOpt_user_id(user_id);
				listAttach.add(attach);
								
			}        
        }
        //System.out.println(listAttach);
		List<Attach> newListAttach=FileUtil.moveFile(listAttach,"party_work");
			
		//System.out.println("ATTACH"+newListAttach);
		if(newListAttach!=null){
		for(Attach attach:newListAttach){
			int a = attachDao.insertAttach(attach);
			//System.out.println(a);
				
			}
		}
		return n;
	}

	
	/**
	 * 删除入党申请
	 */
	@SystemServiceLog(description=Constants.DELETEAPPLY)
	public int deleteApply(String apply_id, HttpServletRequest req) throws ApplyNotFoundException {
		if(apply_id==null||apply_id.trim().isEmpty()){
			throw new ApplyNotFoundException("选择要删除的入党申请");
		}
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null){
			throw new ApplyNotFoundException("重新登录");
		}
		int n = applyDao.deleteApply(apply_id,org_id);
		if(n!=1){
			throw new ApplyNotFoundException("删除失败");
		}
		return n;
	}


	@SystemServiceLog(description=Constants.UPDATEAPPLY)
	public int updateApply(ApplyParam apply, HttpServletRequest req) throws ApplyNotFoundException {
		String certificateReg = "(^\\d{15}$)|(^\\d{18}$)|(^\\d{17}(\\d|X|x)$)";
		if(apply==null){
			throw new ApplyNotFoundException("请填写申请资料！");
		}
		HttpSession session = req.getSession();
		String user_id = (String) session.getAttribute("id");
		String org_id = (String)session.getAttribute("org_id");
		if(user_id==null){
			throw new ApplyNotFoundException("请重新登录！");
		}
		if(apply.getUser_pic()==null||apply.getUser_pic().trim().isEmpty()){
			throw new ApplyNotFoundException("请上传头像");
		}
		if(apply.getUser_id()==null||apply.getUser_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写申请人！");
		}
		if(apply.getDept_id()==null||apply.getDept_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写党组织！");
		}
		if(apply.getCertificate()==null||apply.getCertificate().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写身份证！");
		}
		
			
		if(!Pattern.matches(certificateReg,apply.getCertificate())){
			throw new ApplyNotFoundException("请填写正确的身份证号码！");
		}
		
		
		if(apply.getSex()==null||apply.getSex().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写性别！");
		}
		
		if(apply.getNative_place()==null||apply.getNative_place().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写籍贯！");
		}
		
		if(apply.getEducation()==null||apply.getEducation().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写学历！");
		}
		
		if(apply.getApply_flag()==null||apply.getApply_flag().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写入党标识！");
		}
		
		if(apply.getApply_date()==null){
			throw new ApplyNotFoundException("请填写申请时间！");
		}
		
		if(apply.getSponsor()==null||apply.getSponsor().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写介绍人！");
		}
		
		if(apply.getAddress()==null||apply.getAddress().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写地址！");
		}
		
		if(apply.getBirthday()==null||apply.getBirthday().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写出生日期！");
		}
		
		if(apply.getClass_id()==null||apply.getClass_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写职务！");
		}
		
		if(apply.getPost_id()==null||apply.getPost_id().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写岗位！");
		}
		
		if(apply.getTel()==null||apply.getTel().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写固定电话！");
		}
		
		if(apply.getTel_m()==null||apply.getTel_m().trim().isEmpty()){
			throw new ApplyNotFoundException("请填写移动电话！");
		}
		
		
		
		Apply oldApply = applyDao.findApply(apply.getApply_id(),org_id);
		if(oldApply==null){
			throw new ApplyNotFoundException("此申请不存在");
		}
		
		
		
		//对比之后设置修改参数
		Apply newApply = new Apply();
		newApply.setApply_id(apply.getApply_id());
		if(!apply.getUser_pic().equals(oldApply.getUser_pic())){
			newApply.setUser_pic(apply.getUser_pic());
		}
		if(!apply.getDept_id().equals(oldApply.getDept_id())){
			newApply.setDept_id(apply.getDept_id());
		}
		if(!apply.getCertificate().equals(oldApply.getCertificate())){
			newApply.setCertificate(apply.getCertificate());
		}
		
		if(!apply.getSex().equals(oldApply.getSex())){
			newApply.setSex(apply.getSex());
		}
		if(!apply.getNative_place().equals(oldApply.getNative_place())){
			newApply.setNative_place(apply.getNative_place());
		}
		if(!apply.getEducation().equals(oldApply.getEducation())){
			newApply.setEducation(apply.getEducation());
		}
		if(!apply.getApply_flag().equals(oldApply.getApply_flag())){
			newApply.setApply_flag(apply.getApply_flag());
		}
		if(!apply.getApply_date().equals(oldApply.getApply_date())){
			newApply.setApply_date(apply.getApply_date());
		}
		if(!apply.getSponsor().equals(oldApply.getSponsor())){
			newApply.setSponsor(apply.getSponsor());
		}
		if(!apply.getAddress().equals(oldApply.getAddress())){
			newApply.setAddress(apply.getAddress());
		}
		if(!apply.getBirthday().equals(oldApply.getBirthday())){
			newApply.setBirthday(apply.getBirthday());
		}
		if(!apply.getClass_id().equals(oldApply.getClass_id())){
			newApply.setClass_id(apply.getClass_id());
		}
		if(!apply.getPost_id().equals(oldApply.getPost_id())){
			newApply.setPost_id(apply.getPost_id());
		}
		if(!apply.getTel().equals(oldApply.getTel())){
			newApply.setTel(apply.getTel());
		}
		if(!apply.getTel_m().equals(oldApply.getTel_m())){
			newApply.setTel_m(apply.getTel_m());
		}
		
		if(!user_id.equals(oldApply.getOpt_user_id())){
			newApply.setOpt_user_id(user_id);;
		}
		if(apply.getRemark()!=null){
			newApply.setRemark(apply.getRemark());
		}
		if(apply.getState()!=null){
			newApply.setState(apply.getState());
		}
		apply.setUpdate_date(DateUtil.getNowDate(DateUtil.TIME_FMT));
		
		if(!apply.getUser_pic().equals(oldApply.getUser_pic())){
			String newPath = FileUtil.moveImage(apply.getUser_pic(), "party_work");
			newApply.setUser_pic(newPath);
		}
		
		/**
		 * 移动头像
		 */
		
		newApply.setOrg_id(org_id);
		int n = applyDao.updateApply(newApply);		
		if(n!=1){
			throw new ApplyNotFoundException("修改失败");
		}
		
		List<Attach> listAttach = new ArrayList<Attach>();
		
		if(apply.getListAttach()!=null&&!apply.getListAttach().trim().isEmpty()){
			String str=apply.getListAttach().trim();
			//System.out.println(str);
			JSONArray json=JSONArray.fromObject(str);
			//System.out.println("l="+listAttach.size());
        
			for(int i=0;i<json.size();i++){

				//System.out.println("打桩2："+json.get(i));
				Object check=json.get(i);
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象
				
	
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				Attach attach=new Attach();
				attach.setMessage_no(apply.getApply_id());
				attach.setAttach_type(1);
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id((String) session.getAttribute("org_id"));
				attach.setOpt_user_id(user_id);
				listAttach.add(attach);
								
			}        
        }
        //System.out.println(listAttach);
		List<Attach> newListAttach=FileUtil.moveFile(listAttach,"party_work");
			
		//System.out.println("ATTACH"+newListAttach);
		if(newListAttach!=null){
		for(Attach attach:newListAttach){
			int a = attachDao.insertAttach(attach);
			//System.out.println(a);
				
			}
		}
		return n;
	}


	public Apply findApply(String apply_id, HttpServletRequest req) throws ApplyNotFoundException {
		if(apply_id==null||apply_id.trim().isEmpty()){
			throw new ApplyNotFoundException("选择查询的申请");
		}
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null){
			throw new ApplyNotFoundException("重新登录");
		}
		Apply apply = applyDao.findApply(apply_id,org_id);
		if(apply==null){
			throw new ApplyNotFoundException("此申请不存在");
		}
		return apply;
	}


	public int deleteAllApply(String[] apply_ids, HttpServletRequest req) throws ApplyNotFoundException {
		if(apply_ids==null){
			throw new ApplyNotFoundException("选择要删除的申请");
		}
		if(apply_ids.length<=0){
			throw new ApplyNotFoundException("没有要删除的申请");
		}
		HttpSession session = req.getSession();
		String user_id = (String) session.getAttribute("id");
		if(user_id==null){
			throw new ApplyNotFoundException("重新登录");
		}
		int n = applyDao.deleteAllApply(apply_ids);
		if(n<=0){
			throw new ApplyNotFoundException("删除失败");
		}
		return n;
	}


	public List<UserAndApply> findAllApply(FindApplyParam param,HttpServletRequest req) throws ApplyNotFoundException {
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null){
			throw new ApplyNotFoundException("重新登录");
		}
		Integer page = param.getPage();
		Integer limit = param.getLimit();
		Integer start = null;
		if(limit==null&&page!=null){
			limit = paging.getPageSize();
			start=(page-1)*limit;
		}
		if(page==null){
			start = null;
			limit = null;
		}
		if(limit!=null&&page!=null){
			start = limit*(page-1);
		}		
		param.setStart(start);
		param.setOrg_id(org_id);
		List<UserAndApply> list = applyDao.findAllApply(param);
		
		return list;
	}


	public UserAndApply findApplyById(String apply_id, HttpServletRequest req) throws ApplyNotFoundException {
		if(apply_id==null||apply_id.trim().isEmpty()){
			throw new ApplyNotFoundException("选择查询的申请");
		}
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null){
			throw new ApplyNotFoundException("重新登录");
		}
		UserAndApply apply = applyDao.findApplyById(apply_id,org_id);
		if(apply==null){
			throw new ApplyNotFoundException("此申请不存在");
		}		
		return apply;
	}


	public String findApplyCount(FindApplyParam param, HttpServletRequest req) throws ApplyNotFoundException {
		HttpSession session = req.getSession();
		String org_id = (String) session.getAttribute("org_id");
		if(org_id==null){
			throw new ApplyNotFoundException("重新登录");
		}
		param.setOrg_id(org_id);
		String str = applyDao.findApplyCount(param);
		return str;
	}

	
	
	
		
	
}
